import pika

try:
    # 设置RabbitMQ连接参数
    credentials = pika.PlainCredentials("cloud", "7#BD2CFc3TBV}7m7z")
    parameters = pika.ConnectionParameters(
        host="common.services.prod.wenwo.com",
        port=35672,
        virtual_host="/",
        credentials=credentials,
    )

    # 建立到RabbitMQ的连接
    connection = pika.BlockingConnection(parameters)
    channel = connection.channel()

    # 声明队列
    queue_name = "test_queue_prod"
    channel.queue_declare(queue=queue_name, durable=True)

    # 发送消息到队列
    message = "Hello, RabbitMQ!"
    channel.basic_publish(
        exchange="",
        routing_key=queue_name,
        body=message,
        properties=pika.BasicProperties(delivery_mode=2),
    )
    print(f"Sent {message}")

    # 定义接收消息的回调函数
    def callback(ch, method, properties, body):
        print(f"Received {body}")
        ch.basic_ack(delivery_tag=method.delivery_tag)

    # 等待接收消息
    channel.basic_consume(
        queue=queue_name, on_message_callback=callback, auto_ack=False
    )
    print("Waiting for messages. To exit press CTRL+C")
    channel.start_consuming()

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    if "connection" in locals() and connection.is_open:
        connection.close()
        print("Connection closed")
